/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.servlets.validation;

import com.codemagi.servlets.AppException;
import com.codemagi.servlets.BaseServlet;
import com.codemagi.util.CollectionUtils;
import com.codemagi.util.Utils;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;

/**
 * Validate that an input is a comma-delimited Set of valid Integers
 */
public class SetOfIntegersValidator implements IValidator {

    protected static final String MSG_INVALID_INTEGER = "Invalid number entered. Please check your data and try again.";

    private String DELIMITER = ",";

    public SetOfIntegersValidator() {
	//nada
    }

    public SetOfIntegersValidator(String delimiter) {
	DELIMITER = delimiter;
    }

    public Object validate(Object obj, HttpServletRequest request) throws AppException {

	//sanity check
	if (Utils.isEmpty(obj)) return null;

	if (obj instanceof Integer) {
	    Set<Integer> output = new HashSet<Integer>(1);
	    output.add((Integer)obj);

	    return output;
	}

	if (obj instanceof String) {
	    Set<String> inputs  = CollectionUtils.unDelimitAsSet((String)obj, DELIMITER);
	    Set<Integer> output = new LinkedHashSet<Integer>(inputs.size());

	    for (String sInput : inputs) {
		Integer input = BaseServlet.convertInteger( (String)sInput, true );

		output.add(input);
	    }

	    return output;
	}

	if (obj instanceof List) {
	    List<String> inputs = (List<String>)obj;
	    Set<Integer> output = new LinkedHashSet<Integer>(inputs.size());

	    for (String sInput : inputs) {
                Integer input = BaseServlet.convertInteger( (String)sInput, true );

                output.add(input);
            }

            return output;
	}

	return obj;
    }

}
